package com.controller;

import com.util.OSSUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@Controller
public class UploadController extends BaseController {

    @GetMapping("goUpload")
    public String goUpload(HttpServletRequest request) {
        request.setAttribute("Result", request.getParameter("Result"));
        return "upload";
    }

    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam(name = "file") MultipartFile file, HttpServletRequest request) {
        String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileUUIDName = UUID.randomUUID().toString().replace("-", "") + suffix;

        try {
            String uploadFileName = OSSUtils.uploadFile(file, "huadian/", fileUUIDName);
            request.setAttribute("fileName", fileUUIDName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "upload_re";
    }
}
